package pers.elonnsu.springbootmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import pers.elonnsu.springbootmall.exception.MallException;
import pers.elonnsu.springbootmall.exception.MallExceptionEnum;
import pers.elonnsu.springbootmall.model.dao.CategoryMapper;
import pers.elonnsu.springbootmall.model.pojo.Category;
import pers.elonnsu.springbootmall.model.request.AddCategoryReq;
import pers.elonnsu.springbootmall.model.vo.CategoryVO;
import pers.elonnsu.springbootmall.service.CategoryService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Resource
    private CategoryMapper categoryMapper;

    /**
     * 增加目录分类
     *
     * @param addCategoryReq name 目录名
     *                       type 目录层级
     *                       parentId 父目录的ID
     *                       orderNum 排序
     */
    @Override
    public void addCategory(AddCategoryReq addCategoryReq) {
        Category categoryOld = categoryMapper.selectByName(addCategoryReq.getName());
        if (categoryOld != null) {
            throw new MallException(MallExceptionEnum.NAME_EXISTED);
        }
        Category category = new Category();
        BeanUtils.copyProperties(addCategoryReq, category);
        int count = categoryMapper.insertSelective(category);
        if (count == 0) {
            throw new MallException(MallExceptionEnum.INSERT_FAILED);
        }
    }

    /**
     * 后台：增加目录分类
     *
     * @param updateCategory 需更新的对象
     */
    @Override
    public void update(Category updateCategory) {
        if (updateCategory.getName() != null) {
            Category categoryOld = categoryMapper.selectByName(updateCategory.getName());
            if (categoryOld != null && !categoryOld.getId().equals(updateCategory.getId())) {
                throw new MallException(MallExceptionEnum.NAME_EXISTED);
            }
        }
        int count = categoryMapper.updateByPrimaryKeySelective(updateCategory);
        if (count == 0) {
            throw new MallException(MallExceptionEnum.UPDATE_FAILED);
        }
    }

    @Override
    public void deleteById(Integer id) {
        Category categoryOld = categoryMapper.selectByPrimaryKey(id);
        if (categoryOld == null) {
            throw new MallException(MallExceptionEnum.DELETE_FAILED);
        }
        int count = categoryMapper.deleteByPrimaryKey(id);
        if (count == 0) {
            throw new MallException(MallExceptionEnum.DELETE_FAILED);
        }
    }

    @Override
    public PageInfo<Category> listCategoryForAdmin(Integer pageNum, Integer pageSize) {
        // PageHelper.startPage()方法是对之后查询中的最近一个查询进行分页。
        PageHelper.startPage(pageNum, pageSize, "type,order_num");
        List<Category> categories = categoryMapper.selectAllCategories();
        return new PageInfo<>(categories);
    }

    @Override
    @Cacheable(value = "listCategoryForCustomer")
    public List<CategoryVO> listCategoryForCustomer(Integer parentId) {
        List<CategoryVO> categoryVOList = new ArrayList<>();
        findCategoriesByRecursion(categoryVOList, parentId);
        return categoryVOList;
    }

    /**
     * Helper 方法，为List<CategoryVO> listForCustomer()方法递归查询分类
     *
     * @param categoryVOList 分类目录列表
     * @param parentId       父目录的编号
     */
    private void findCategoriesByRecursion(List<CategoryVO> categoryVOList, Integer parentId) {
        // 递归获取所有子类别，并组合成目录树
        List<Category> categoryList = categoryMapper.selectCategoriesByParentId(parentId);
        if (!CollectionUtils.isEmpty(categoryList)) {
            for (Category category : categoryList) {
                CategoryVO categoryVO = new CategoryVO();
                BeanUtils.copyProperties(category, categoryVO);
                categoryVOList.add(categoryVO);
                findCategoriesByRecursion(categoryVO.getChildCategory(), categoryVO.getId());
            }
        }
    }
}
